import board
import busio
import adafruit_bmp280
import logging
import time
from config.config import BMP280_I2C_ADDR

logger = logging.getLogger(__name__)

class BMP280Sensor:
    def __init__(self):
        logger.info(f"初始化BMP280传感器，I2C地址：0x{BMP280_I2C_ADDR:02x}")
        i2c = busio.I2C(board.SCL, board.SDA)
        self.sensor = adafruit_bmp280.Adafruit_BMP280_I2C(i2c, address=BMP280_I2C_ADDR)
        self.sensor.sea_level_pressure = 1013.25

    def read(self):
        """读取温度和气压数据"""
        try:
            data = {
                'temperature': self.sensor.temperature,
                'pressure': self.sensor.pressure,
                'altitude': self.sensor.altitude
            }
            logger.debug(f"BMP280读取数据：温度={data['temperature']:.1f}°C, 气压={data['pressure']:.1f}hPa")
            return data
        except Exception as e:
            logger.error(f"BMP280读取失败: {str(e)}")
            return None
    
    def read_average(self, times=5, interval=2):
        """多次读取取平均值"""
        logger.info(f"开始BMP280多次读取，次数={times}，间隔={interval}秒")
        temps = []
        pressures = []
        
        for i in range(times):
            data = self.read()
            if data:
                temps.append(data['temperature'])
                pressures.append(data['pressure'])
            time.sleep(interval)
            
        if not temps or not pressures:
            logger.error("BMP280多次读取全部失败")
            return None
            
        avg_data = {
            'temperature': sum(temps)/len(temps),
            'pressure': sum(pressures)/len(pressures)
        }
        logger.info(f"BMP280平均值：温度={avg_data['temperature']:.1f}°C, 气压={avg_data['pressure']:.1f}hPa")
        return avg_data